package com.demo.exception;

import com.demo.common.ErrorDetail;
import com.demo.common.Result;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ApiException.class)
    public ResponseEntity<Result> handleApiException(ApiException e) {
        return ResponseEntity
                .status(e.getErrorDetail().getHttpCode())
                .body(Result.error(e.getErrorDetail()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handleException(Exception e) {
        ErrorDetail detail = ErrorDetail.builder()
                .httpCode(500)
                .message("系统内部错误")
                .reason(e.getMessage())
                .build();

        return ResponseEntity.internalServerError()
                .body(Result.error(detail));
    }
}